var express = require('express');
var router = express.Router();
var JWT = require('../public/javascripts/jwt');
var createError = require('http-errors');

const whiteList = ['/user/login']; // 登录不需要验证token

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

// 全局拦截
router.all('/*', (req, res, next) => {
  // if (whiteList.some(path => path === req.path)) return next(createError(404));
  const token = req.get('Authorization');
  const result = whiteList.some(path => path === req.path) || (token && JWT.verifyToken(token.split(' ')[1]));
  // if (token) {
    if (result) {
      // next(createError(404));
      next()
    } else {
      res.status(401).send({
        code: 401,
        msg: '登录信息已失效，请重新登录'
      })
    }
  // } else {
  //   res.status(401).send({
  //     code: 401,
  //     msg: '未携带token'
  //   })
  //   // res.send({
  //   //   code: 401,
  //   //   msg: '未携带token'
  //   // })
  //   // next()
  // }
})

module.exports = router;
